package com.huluobo.kotlinim1911a.contract.contact

import android.util.Log
import com.huluobo.kotlinim1911a.data.ContactListItem
import com.huluobo.kotlinim1911a.db.Contact
import com.huluobo.kotlinim1911a.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2022/6/27.
 */
class ContactPresenter(private val view: ContactContract.View) : ContactContract.Presenter {

    val contactListItems = mutableListOf<ContactListItem>()
    override fun loadContacts() {
        doAsync {
            try {
                contactListItems.clear()
                IMDatabase.instance.deleteAllContacts()
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer

                //按照首字符来进行排序
                userNames.sortBy {
                    it[0]
                }

                //什么时候需要显示首字符
                userNames.forEachIndexed { index, it ->
                    //1.当index=0的时候,2.对比上一位的首字符与当前首字符不符
                    val showFirstLetter = index == 0 || it[0] != userNames[index - 1][0]
                    val contactListItem =
                        ContactListItem(it, it[0].uppercaseChar(), showFirstLetter)
                    contactListItems.add(contactListItem)
                    val contact = Contact(mutableMapOf("name" to it))
                    IMDatabase.instance.saveContact(contact)
                }
//                userNames.forEach {
//                    //拿到每一个联系的对象(名字,首字符,是否显示首字符)
//                    //it代表usernames里面的每一个string,uppercaseChar转换为大写字母
//                    val contactListItem = ContactListItem(it, it[0].uppercaseChar())
//                    contactListItems.add(contactListItem)
//                }
                runOnUIThread { view.onLoadContactsSuccess() }
            } catch (e: HyphenateException) {
                runOnUIThread { view.onLoadContactsFailed() }
            }
        }
    }
}